<template>
    <div class="edit">
        <h3 style='text-align:center;font-weight:700;margin:10px'>新增互联网收费项目</h3>
        <div class="main">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="90" label-position="left">
                <Row gutter="32" class="infobox">
                    <p class="title">项目基本信息</p>
                    <div class="mainbox">
                        <Col span="8">
                            <FormItem prop="projectCategory" label="项目类别：" class="hongdian">
                                <Select v-model="formValidate.projectCategory" style='width:100%;' >
                                    <Option style='text-align:center;' :value="item.id" v-for='item in projectCategoryList' :key='item.id'>{{ item.name }}</Option>
                                </Select>
                            </FormItem>
                            <FormItem label="项目收费依据：" :label-width="110">
                                <Input v-model="formValidate.chargingBasis" :maxlength="50" placeholder="输入收费依据" style='width:100%;'></Input>
                            </FormItem>
                            <FormItem label="启用标识：">
                                <iSwitch size="large" v-model="formValidate.ienable" @on-change="changeStatus(formValidate.ienable)">
                                    <span slot="open">开启</span>
                                    <span slot="close">关闭</span>
                                </iSwitch>
                            </FormItem>                       
                        </Col>
                        <Col span="8">
                            <FormItem label="项目名称：" prop="techName" class="hongdian">
                                <Input v-model="formValidate.techName" :maxlength="50" placeholder="输入项目名称" style='width:100%;'></Input>
                            </FormItem>
                            <FormItem prop="chargingUnit" label="项目收费单位：" :label-width="110" class="hongdian">
                                <Select v-model="formValidate.chargingUnit" style='width:100%;'>
                                    <Option style='text-align:center;' :value="item.id" :key='item.id' v-for='item in chargingUnit'>{{ item.name }}</Option>
                                </Select>
                            </FormItem>
                            <FormItem label="是否为预约项：" :label-width="100">
                                <iSwitch size="large" v-model="formValidate.isubscribe" @on-change="changeisubscribe(formValidate.isubscribe)" :disabled="isubscribeDisable">
                                    <span slot="open">开启</span>
                                    <span slot="close">关闭</span>
                                </iSwitch>
                            </FormItem>
                        </Col>
                        <Col span="8"> 
                            <FormItem label="所属科室：">
                                <Select v-model="formValidate.executiveDeptId"  style='width:100%;'>
                                    <Option
                                        v-for="item in departmentList"
                                        :value="item.id"
                                        :key="item.id"
                                        style='text-align:center'
                                    >{{item.deptNickname}}</Option>
                                    <!-- dictName -->
                                </Select>
                            </FormItem>
                            <FormItem prop="chargingPrice" label="项目平台收费标准（元）：" :label-width="170" class="hongdian">
                                <InputNumber :max="9999" :min="0" v-model="formValidate.chargingPrice" placeholder="0.00" style='width:100%;'></InputNumber>
                            </FormItem>
                            <FormItem label="患者可否直接预约：" :label-width="120">
                                <iSwitch size="large" v-model="formValidate.ipatientAppointment" :disabled="ipatientAppointmentDisable">
                                    <span slot="open">开启</span>
                                    <span slot="close">关闭</span>
                                </iSwitch>
                            </FormItem>
                        </Col>  
                        <Col span="24">
                            <FormItem label="项目详情：">
                                <vueEditor
                                    id="healthEditor"
                                    :textHtml="formValidate.projectDetails"
                                    :urlCode="urlCode"
                                    @valueHandle="afterChange"
                                    style='width:100%;margin:0'
                                ></vueEditor>
                            </FormItem>        
                        </Col>
                        <Col span="24">
                            <FormItem label="适用人群：">
                                <Input v-model="formValidate.forPeople" type="textarea" maxlength="250" :autosize="{minRows: 2,maxRows: 5}" placeholder="输入适用人群："></Input>
                            </FormItem>       
                        </Col>
                        <Col span="24">
                            <FormItem label="项目特点：">
                                <Input v-model="formValidate.projectFeatures" type="textarea" maxlength="250" :autosize="{minRows: 2,maxRows: 5}" placeholder="输入项目特点：" ></Input>
                            </FormItem>    
                        </Col>
                        <Col span="24">
                            <FormItem label="预约须知：">
                                <Input v-model="formValidate.appointmentNotice" type="textarea" maxlength="250" :autosize="{minRows: 2,maxRows: 5}" placeholder="输入预约须知："></Input>
                            </FormItem>   
                        </Col>
                    </div>                   
                </Row>
                <Row gutter="32" class="infobox">
                    <p class="title">院内系统项目关联</p>    
                    <div style='margin-bottom:35px;'>   
                        <span class="tit">项目关联：</span>
                        <Select v-model="combinationType" style='width:150px;'>
                            <Option style='text-align:center;' :value="index+1" v-for='(item,index) in correlationlist' :key='index'>{{ item.name }}</Option>
                        </Select>              
                        <Input v-model.trim="xmmc" placeholder="请输入项目或组合名称检索" style="width: 200px;margin-left:10px;margin-right:10px"></Input>
                        <Button type="primary" icon="ios-search" @click='pageChangexm(1)'>查询</Button>
                    </div>
                    <div class = 'footerList'>
                        <div class="left">
                            <p>可选项目</p>                  
                            <Table stripe :columns="columns2" :data="data2"></Table>
                            <Page :total="total"  :page-size='pageSize' :current = 'pageNo' style='margin:10px 0;text-align: center;' @on-change='pageChangexm'/>
                        </div>
                        <div class="right">
                            <p>已选项目</p>
                            <Table stripe :columns="columns3" :data="data3" ref="table3">
                                <template slot="num" slot-scope="props" >
                                    <InputNumber type="number" v-model="props.row.num" :min='1' :max="999" placeholder="输入数量" @on-change='money'></InputNumber>  
                                </template>
                            </Table>
                            <p v-if="this.data3.length" style="border:1px solid #ccc;border-top:none; border-bottom:none;font-size: 14px; padding-left: 200px;">总计：<span>{{zj}}&nbsp;&nbsp;元</span></p>
                        </div>
                    </div>
                </Row>   
            </Form>
            <div style='textAlign: center;'>
                <Button type='primary' @click='handleSubmit("formValidate")' :disabled="isDisable" style="width:95px;height:35px;">
                    <Icon type="ios-checkmark" style="margin-right: 5px" />确认添加
                </Button>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <Button @click='handleReset("formValidate")' style="width:75px;height:35px;">
                    <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
                </Button>
            </div>
        </div> 
    </div>
</template>
<script>
import api from "@/api/commonApi";
import code from "@/configs/base.js";
import vueEditor from "@/components/vueEditor";
export default {
    components: {
        vueEditor
    },
    data(){
        return{
            hospitalId: sessionStorage.getItem("hospitalId"),
            isBack: 2,
            id: '',
            jsonObj: { json: '{"urlCode":"'+ code.urlCode.healthEducation +'"}' },
            urlCode: '{"urlCode":"'+ code.urlCode.richText+'"}',
            isDisable: false,//表单重复提交
            isubscribeDisable: false,//禁止预约项点击
            ipatientAppointmentDisable: false,//禁止患者预约项点击
            moldType: '',
            projectlist:[
                {dictName: '全部', dictValue: 0},            
                {dictName: '健康咨询', dictValue: 1},            
                {dictName: '巡诊', dictValue: 2},            
                {dictName: '检查项目', dictValue: 3},            
                {dictName: '检验项目', dictValue: 4},            
                {dictName: '治疗项目', dictValue: 5},  
                {dictName: '其他', dictValue: " "},  
            ],
            projectStatus: null,
            // 项目类型列表
            projectCategoryList: [              
                {
                    name:"检查项目",
                    id:'3'
                },
                {
                    name:"检验项目",
                    id:'4'
                },
                {
                    name:"治疗项目",
                    id:'5'
                },
                {
                    name:"手术项目",
                    id:'6'
                },
                {
                    name:"体检项目",
                    id:'7'
                },
                {
                    name:"其他",
                    id:'8'
                },
            ],
            //项目关联
            correlationlist:[
                // { name:"全部", id:'1'},
                { name:"单项", id:'1'},
                { name:"组合项", id:'2'}
            ],
            // 咨询列表
            consultList: [
                { name: "通用", id: 1 },
                { name: "门诊预约", id: 2 },
                { name: "住院复查", id: 3 },
            ],
            Name: "",
            // 分页数据
            count: 10,
            pageNo: 1,
            pageSize: 10,
            inspection: '',
            typeName: '',
            tsort: '',
            relatingCodes: '',
            // 左侧医疗团队成员
            columns2:[
                {
                    title:"排序",
                    align:"center",
                    key:"sum",
                    render: (h, params) => {
                        let sum = (this.pageNo-1)*this.pageSize + params.index +1;
                        return h("span", sum);
                    }
                },
                {
                    title:"项目名称",
                    align:"center",
                    key:"itemName"
                },
                {
                    title:"单价",
                    align:"center",
                    key:"chargingPrice"
                },
                {
                    title:"设置",
                    align:"center",
                    render:(h,params) => {
                        let row = params.row;
                        return [
                            h('a', {
                                on:{
                                    'click':() => {
                                        console.log(row);
                                        let flag = false;
                                        this.data3.forEach((item,index) => {
                                            if(row.id == item.id){
                                                flag = true;
                                            }
                                        })
                                        if(flag){
                                            this.$Message.error("请勿重复添加");
                                            return;
                                        }
                                        row.num = 1
                                        this.data3.push(row)
                                        this.data3.forEach((item,index) => {
                                            // 排序
                                            item.sum = this.addZeros(index)
                                        })
                                        this.data2.splice(row._index,1);
                                        this.money()
                                    }
                                }
                            }, '添加')
                        ]
                    }
                }
            ],
            data2:[],
            total: '',
            // 右侧医疗团队成员
            columns3:[
                {
                    title:"排序",
                    align:"center",
                    key:"sum"
                },
                {
                    title:"项目名称",
                    align:"center",
                    key:"itemName"
                },
                {
                    title:"单价",
                    align:"center",
                    key:"chargingPrice"
                },
                {
                    key: "num",
                    title: "数量",
                    align: "center",
                    render:(h,params) => {
                        this.data3[params.index] = params.row
                            return [                          
                                h('div', 
                                    this.$refs.table3.$scopedSlots.num({
                                        row: params.row,
                                        idx: params.row._index
                                    
                                    })
                                )
                            ]                         
                    }
                },
                {
                    title:"设置",
                    align:"center",
                    key:"sum",
                    render:(h,params) => {
                        let row = params.row
                        return [
                            h('a',{
                                on:{
                                    'click':() => {
                                        row.role = ''
                                        this.handleRemove(row);
                                    }
                                }

                            },'移除')
                        ]
                    }
                }
            ],
            data3:[],
            xmmc: '',
            // 表单验证以及项目详细数据
            formValidate: {
                //项目分类
                projectCategory: '',
                //所属科室
                executiveDept: "",
                executiveDeptId: "",
                //使用业务模块
                modular: "",
                // 项目名称
                techName: "",
                // 收费单位
                chargingUnit: "",
                //收费标准
                chargingPrice: "",
                // 收费依据
                chargingBasis: "",
                //项目详情
                projectDetails: "",
                //适用人群
                forPeople: "",
                //项目特点
                projectFeatures: "",
                //预约须知
                appointmentNotice: "",
                // 业务模块
                modular: "",
                // 启用标识
                ienable: true,
                //是否为预约项
                isubscribe: true,
                //是否患者可以直接预约
                ipatientAppointment: true,
                // 标识Id
                id: "",
                // 医院ID
                hospitalId: sessionStorage.getItem("hospitalId"),
            },
            ruleValidate: {
                projectCategory: [{ required: true, message: '请选择项目', trigger: 'change' }],
                classify: [{ required: true, message: '请选择项目分类', trigger: 'change' }],
                techName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
                chargingUnit: [{ required: true, message: '请选择收费单位', trigger: 'change' }],
                chargingPrice: [{ required: true, message: '请输入收费单价', trigger: 'blur', type:'number' }],
                modular: [{ required: true, message: '请选择项目', trigger: 'change', type:'number'}],
            },
            //执行科室列表
            departmentList: [],           
            // 收费单位列表
            chargingUnit: [],
            // 业务模块
            modular: [],
            Allmodular: ["健康咨询","问诊","复诊","续方","用药咨询"],

            zj: 0
        }
    },
    created() {
        this.hospitalId = parseInt(this.$route.query.hospitalId);
        this.pageNo = this.$route.query.pageNo?parseInt(this.$route.query.pageNo):1;     
        if(this.formValidate.ienable == false ){
            this.formValidate.isubscribe = false
            this.isubscribeDisable = true   
        }
        if(this.formValidate.isubscribe == false){
            this.formValidate.ipatientAppointment = false
            this.ipatientAppointmentDisable = true   
        }
    },
    mounted () {
        // 页面查询的科室选择框
        this.loadingDepartment()
        //加载收费列表
        this.getfeeunitenum()
    },
    methods:{
        //计算总价
        money(){
            this.zj = 0
            if (this.data3 && this.data3.length ) {               
                this.data3.map(item => {     
                     if(item.num){
                        this.zj += Number(item.chargingPrice)*Number(item.num);
                     }           
                })
            }
            this.zj = this.zj.toFixed(2);
            console.log(this.data3)
        },
        //是否启用控制其他俩个按扭的状态
        changeStatus(val){
            if(val == false){
                this.formValidate.isubscribe =  false
                this.formValidate.ipatientAppointment = false
                this.isubscribeDisable = true
                this.ipatientAppointmentDisable = true              
            } else {
                this.isubscribeDisable = false           
            }
        },
        changeisubscribe(val){
            if(val == false){
                this.formValidate.ipatientAppointment = false
                this.ipatientAppointmentDisable = true               
            } else {
                this.ipatientAppointmentDisable = false
            }
        },
        //富文本编辑器
        afterChange(val) {
            this.formValidate.projectDetails = val;
        },
         //表格
        selectChange(selections) {
            this.selections = selections;
        },
        disabledRole(){
            return this.data3.some(item =>{
                return parseInt(item.role) == 1
            })
        },
        // 加载收费列表
        getfeeunitenum(){
            this.$axios.post(api.findFeeEnum,{}).then(resp => {
                if(resp.data.success) {
                    let ret = resp.data;
                    this.chargingUnit = ret.object;
                    console.log(this.chargingUnit)
                }
            })
         },
         // 页面查询的科室选择框
        loadingDepartment(){
            let url = api.findDeptName
            let params = {
                hospitalId : this.formValidate.hospitalId,
                medicalTechnology: 1
            }
            this.packageAxios(this,url,params,(res)=>{
                console.log(res);
                if(res.data.success) {
                    let ret = res.data.object;
                    console.log(ret)
                    this.departmentList = ret;
                } else {
                    this.$Message.error("加载失败")
                }
            })
        },
        //删除选择的HIS收费项目
        handleRemove(val){
            this.data3.splice(val._index, 1)
            this.data2.push(val)
            //计算总价
            this.money()
        },
        //获取HIS收费项目
        getHisPage(){
            let params = {
                "hospitalId": this.formValidate.hospitalId,
                "pageNo": this.pageNo,
                "pageSize": this.pageSize,   
                "inspection": this.formValidate.projectCategory,
                "combinationType": this.combinationType                 
            }
            if (this.xmmc != "") {
                params.itemName = this.xmmc.trim();
            }
            this.$axios
                .post(api.findMedicalCombination, params)
                .then(resp => {
                     console.log(params)
                    let ret = resp.data.object.records;
                    ret.forEach((item,index) => {
                        // 排序
                        item.sum = this.addZeros(index)
                    })
                    this.data2 = ret
                    this.total = resp.data.object.total
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 保存新增
        handleSubmit (name) {
            this.isDisable = true  //不可点击
            this.$refs[name].validate((valid) => {
                if (valid) {
                    if(String(this.formValidate.chargingPrice).indexOf('.')!=-1 && String(this.formValidate.chargingPrice).split('.')[1].length>2){
                        this.$Message.error('项目平台收费标准请保留两位小数!');
                        this.isDisable = false  //不可点击
                        return;
                    }
                    let url = api.insetTechnologyCombination;
                    let medicalTechnologyCombination = {
                        "hospitalId": this.formValidate.hospitalId,
                        "inspection": this.formValidate.projectCategory,
                        "executiveDeptId": this.formValidate.executiveDeptId,
                        "techName": this.formValidate.techName,
                        "chargingBasis": this.formValidate.chargingBasis,
                        "chargingPrice": this.formValidate.chargingPrice,
                        "chargingUnit": this.formValidate.chargingUnit,
                        "projectDetails": this.formValidate.projectDetails,
                        "forPeople": this.formValidate.forPeople,
                        "projectFeatures": this.formValidate.projectFeatures,
                        "appointmentNotice": this.formValidate.appointmentNotice,
                        "ienable": Number(this.formValidate.ienable),
                        "ipatientAppointment": Number(this.formValidate.ipatientAppointment),
                        "isubscribe": Number(this.formValidate.isubscribe),            
                        "combinationType": 2,     
                    }     
                    this.chargingUnit.forEach(i => {
                        if(i.id == this.formValidate.chargingUnit){
                            medicalTechnologyCombination.chargingUnitName = i.name
                        }
                    })
                    if(this.formValidate.executiveDeptId){
                        this.departmentList.forEach(z => {
                            if(z.id == this.formValidate.executiveDeptId){
                                medicalTechnologyCombination.executiveDeptName = z.deptNickname
                                medicalTechnologyCombination.executiveDept = z.dictType
                            }
                        })    
                    }               
                    let list = 
                    this.data3.map(i=>({
                            "chargeId": i.id,
                            "combinationType": i.combinationType,  
                            "num": i.num,
                        }))
                    let params = {
                        list,
                        medicalTechnologyCombination
                    }
                    console.log("新增参数",JSON.stringify(params));
                    if(params.list.length == 0){
                        this.$Message.error('请选择院内系统关联项目')
                        setTimeout(() => {
                            this.isDisable = false;//放开点击了
                        }, 1000);
                    } else {
                        this.$axios.post(url, params).then(res => {
                            if(res.data.success) {
                                this.$Message.success('保存成功')
                                this.isDisable = false;//放开点击了
                                // 弹窗数据初始化
                                this.handleReset('formValidate');
                                this.modalStatus = false;
                            } else {
                                this.isDisable = false;//放开点击了
                                this.$Message.error(res.data.message)
                            }
                        }).catch(err => {
                            this.isDisable = false;//放开点击了
                            console.log(err);
                        });
                    }                    
                } else {
                    this.$Message.error('请完整填写必填项!');
                    this.isDisable = false  //不可点击
                }
            })
        },
        // 取消保存
        handleReset (name) {
            this.$refs[name].resetFields();
            this.formValidate.projectCategory = ''
            // 项目名称
            this.formValidate.techName = ''
            // 物价码
            this.formValidate.priceCode = ''
            // 收费依据
            this.formValidate.chargingBasis = ''
            // 收费单位
            this.formValidate.chargingUnit = ''
            // 收费标准
            this.formValidate.chargingPrice = ''
            //项目详情
            this.formValidate.projectDetails = ''
            //适用人群
            this.formValidate.forPeople = ''
            //项目特点
            this.formValidate.projectFeatures = ''
            //预约须知
            this.formValidate.appointmentNotice = ''
            // 启用标识
            this.formValidate.status = false
            this.formValidate.ipatientAppointment = false
            this.formValidate.isubscribe = false
            // 标识Id
            this.formValidate.id = ''
            this.modalStatus = false
            this.formValidate.consult = ''
            this.formValidate.consultPrice = ''
            let query = this.$route.query
            this.functionJS.queryNavgationTo(
                this,
                "/index/directory/priceManagement/index",
                {type:3,hospitalId:this.hospitalId}
            );
            this.tab = '2'
        },
        pageChangexm(index) {
            this.pageNo = index;
            if (this.xmmc) {
                this.getHisPage(index, this.xmmc);
            } else {
                this.getHisPage(index);
            }
        },
    },
    watch: {
        'pageSize'(nv, ov) {
            this.getDoctorData(this.pageNo)
        },
        formValidate: {
            handler(n) {
                // console.log(n);
            },
            deep: true
        }
    }
}
</script>
<style lang="less" scoped>
.edit{
    padding: 10px 30px;
    width: 100%;
    background: #ffffff;
    box-sizing: border-box;
    .main{
        margin-top:10px; 
        .infobox {
            margin: 10px auto;
            border: 1px solid #f0f0f0;
            box-shadow: 0 4px 3px #ebedf8;
            border-radius: 5px;
            margin-bottom: 20px;
            .mainbox{
                padding: 0 15px;
                .hongdian{
                    margin-left: -10px;
                }
            }
            .title {
                font-size: 20px;
                padding-left: 15px;
                margin-bottom: 20px;
                color: #333;
                height: 40px;
                line-height: 40px;
                background: #ebedf8;         
            }
            .tit{
                font-size:12px;
                color:#495060;
                margin-left: 30px;
            }    
            .footerList{
                width:100%;
                display:flex;
                flex: 1;
                flex-direction:row;
                margin-top: 10px;
                margin-bottom: 20px;
                justify-content: space-between;
                padding: 0 30px;
                .left,.right{
                    width: 49%;
                    border: 1px #ccc solid;
                    p{
                        text-align:center;
                        line-height: 45px;
                    }
                }
            }
        }
    }   
    Button{
        border-radius: 20px;
    }
}
</style>